<template>
    <div class="map-container">
        <div id="container" class="map-content"></div>
        <!-- 显示加载状态或错误信息 -->
        <div v-if="!mapLoaded" class="map-overlay">
            <div class="map-loading">{{ loadingError || '地图加载中...' }}</div>
        </div>
    </div>
</template>
<script>
import { get } from '@/utils/request'

export default {
    data() {
        return {
            map: null,
            mapLoaded: false,
            loadingError: '',
            scriptLoaded: false,
            deviceData: [] // 存储设备位置数据
        }
    },
    mounted() {
        console.log('地图组件挂载，开始加载高德地图');
        // 先获取设备数据，再加载地图
        this.getDeviceData().then(() => {
            this.loadMap();
            
            // 如果5秒后地图仍未加载，重试一次
            setTimeout(() => {
                if (!this.mapLoaded && !this.loadingError) {
                    console.log('地图加载超时，重试一次');
                    this.loadMap();
                }
            }, 5000);
        });
    },
    methods: {
        // 获取设备位置数据
        async getDeviceData() {
            try {
                console.log('开始获取设备位置数据');
                const res = await get('/device/pageQuery', { page: 1, pageSize: 1000 });
                console.log('设备数据响应:', JSON.stringify(res, null, 2));
                
                if (res && res.data && res.data.list) {
                    // 过滤出有有效经纬度的设备
                    this.deviceData = res.data.list.filter(device => {
                        // 检查是否有经纬度数据
                        const hasLocation = device.longitude && device.latitude && 
                                          !isNaN(Number(device.longitude)) && 
                                          !isNaN(Number(device.latitude));
                        
                        if (!hasLocation) {
                            console.log(`设备 ${device.name || device.id} 缺少有效经纬度`);
                        }
                        return hasLocation;
                    });
                    
                    console.log(`获取到 ${this.deviceData.length} 个有位置信息的设备`);
                } else {
                    console.warn('获取设备数据为空或格式不正确');
                    this.deviceData = [];
                }
            } catch (error) {
                console.error('获取设备数据失败:', error);
                this.deviceData = [];
            }
        },
        
        loadMap() {
            // 如果脚本已加载，不再重复加载
            if (this.scriptLoaded) return;
            this.scriptLoaded = true;
            
            try {
                console.log('开始加载高德地图API');
                
                // 检查地图容器
                const container = document.getElementById('container');
                if (!container) {
                    this.loadingError = '地图容器不存在';
                    console.error(this.loadingError);
                    return;
                }
                
                // 设置全局回调
                window.initAMap = () => {
                    console.log('高德地图API加载完成，初始化地图');
                    this.initMapInstance();
                };
                
                // 加载高德地图脚本
                const script = document.createElement('script');
                script.type = 'text/javascript';
                // 添加时间戳避免缓存问题
                script.src = `https://webapi.amap.com/maps?v=1.4.15&key=507df692c135b0e8afb933f0c8018cf6&callback=initAMap&t=${Date.now()}`;
                script.async = true;
                script.onerror = () => {
                    this.loadingError = '地图脚本加载失败，请检查网络';
                    console.error(this.loadingError);
                };
                document.head.appendChild(script);
                
                console.log('地图脚本添加到文档');
            } catch (error) {
                this.loadingError = '地图初始化出错';
                console.error('地图加载错误:', error);
            }
        },
        
        initMapInstance() {
            try {
                if (!window.AMap) {
                    this.loadingError = 'AMap对象不存在';
                    console.error(this.loadingError);
                    // 使用离线地图回退方案
                    this.useOfflineMap();
                    return;
                }
                
                // 创建地图实例
                this.map = new AMap.Map('container', {
                    zoom: 4,
                    center: [116.397428, 39.90923], // 北京
                    viewMode: '2D',
                    resizeEnable: true
                });
                
                // 监听地图加载完成事件
                this.map.on('complete', () => {
                    console.log('地图渲染完成');
                    this.mapLoaded = true;
                    
                    // 地图加载完成后添加设备标记
                    this.addDeviceMarkers();
                });
                
                // 监听地图加载错误事件
                this.map.on('error', () => {
                    console.error('地图渲染错误');
                    // 使用离线地图回退方案
                    this.useOfflineMap();
                });
                
                console.log('地图实例创建成功');
            } catch (error) {
                this.loadingError = '地图创建失败';
                console.error('创建地图实例错误:', error);
                // 使用离线地图回退方案
                this.useOfflineMap();
            }
        },
        
        // 添加设备标记
        addDeviceMarkers() {
            if (!this.map || !this.deviceData.length) {
                console.log('没有地图实例或设备数据为空，无法添加标记');
                return;
            }
            
            console.log(`开始添加 ${this.deviceData.length} 个设备标记`);
            
            // 创建设备标记点
            const markers = this.deviceData.map(device => {
                // 确保经纬度是数值
                const lng = Number(device.longitude);
                const lat = Number(device.latitude);
                
                if (isNaN(lng) || isNaN(lat)) {
                    console.error(`设备 ${device.name || device.id} 经纬度无效: ${device.longitude}, ${device.latitude}`);
                    return null;
                }
                
                // 创建标记
                const marker = new AMap.Marker({
                    position: [lng, lat],
                    title: device.name || `设备${device.id}`,
                    icon: new AMap.Icon({
                        size: new AMap.Size(25, 34),
                        image: device.status === '在线' ? 
                               'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png' : 
                               'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png',
                        imageSize: new AMap.Size(25, 34)
                    }),
                    extData: device
                });
                
                // 创建信息窗体
                const infoWindow = new AMap.InfoWindow({
                    content: `<div class="info-window">
                        <div class="info-title">${device.name || '未命名设备'}</div>
                        <div class="info-body">
                            <p>设备ID: ${device.id || '未知'}</p>
                            <p>状态: ${device.status || '在线'}</p>
                           
                        </div>
                    </div>`,
                    offset: new AMap.Pixel(0, -30)
                });
                
                // 绑定点击事件
                marker.on('click', () => {
                    infoWindow.open(this.map, marker.getPosition());
                });
                
                return marker;
            }).filter(marker => marker !== null);
            
            // 批量添加标记到地图
            if (markers.length > 0) {
                this.map.add(markers);
                console.log(`成功添加 ${markers.length} 个设备标记到地图`);
                
                // 调整地图视野到包含所有标记
                if (markers.length > 1) {
                    this.map.setFitView();
                }
            } else {
                console.warn('没有有效的设备标记点可以添加到地图');
            }
        },
        
        // 使用离线地图回退方案
        useOfflineMap() {
            this.loadingError = '使用离线地图显示';
            console.log('启用离线地图回退方案');
            
            // 修正容器ID - 应该使用'container'而不是'amapContainer'
            const mapEl = document.getElementById('container');
            if (!mapEl) {
                console.error('找不到地图容器元素');
                return;
            }

            // 清空现有内容
            mapEl.innerHTML = '';
            
            // 创建离线地图容器
            const offlineMap = document.createElement('div');
            offlineMap.className = 'offline-map';
            
            // 添加标题
            const title = document.createElement('div');
            title.className = 'map-title';
            title.textContent = '设备分布（离线地图）';
            offlineMap.appendChild(title);
            
            // 添加地图内容区域
            const content = document.createElement('div');
            content.className = 'map-content';
            
            // 添加地图背景
            const mapBackground = document.createElement('div');
            mapBackground.className = 'map-background';
            content.appendChild(mapBackground);
            
            // 使用实际设备数据创建城市标记
            // 如果有实际设备数据，使用实际数据；否则使用默认数据
            const cities = this.deviceData.length > 0 ? 
                this.createCityDataFromDevices() : 
                [
                    { name: '北京', class: 'north', devices: 12 },
                    { name: '上海', class: 'east', devices: 18 },
                    { name: '广州', class: 'south', devices: 15 },
                    { name: '成都', class: 'west', devices: 8 },
                    { name: '武汉', class: 'center', devices: 10 }
                ];
            
            cities.forEach(city => {
                const marker = document.createElement('div');
                marker.className = `city-marker ${city.class}`;
                marker.textContent = `${city.name} (${city.devices})`;
                marker.addEventListener('click', () => {
                    alert(`${city.name}有${city.devices}台设备运行中`);
                });
                content.appendChild(marker);
            });
            
            offlineMap.appendChild(content);
            mapEl.appendChild(offlineMap);
            
            this.mapLoaded = true;
            console.log('离线地图加载完成');
        },
        
        // 从设备数据中创建城市数据
        createCityDataFromDevices() {
            // 根据设备地址分组
            const cityGroups = {};
            
            this.deviceData.forEach(device => {
                // 尝试从地址或其他字段提取城市信息
                let city = '未知';
                
                if (device.address) {
                    // 简单处理：从地址中提取第一个城市名
                    const cities = ['北京', '上海', '广州', '深圳', '成都', '武汉', '杭州', '南京', '西安', '重庆'];
                    for (const c of cities) {
                        if (device.address.includes(c)) {
                            city = c;
                            break;
                        }
                    }
                }
                
                if (!cityGroups[city]) {
                    cityGroups[city] = { count: 0, devices: [] };
                }
                
                cityGroups[city].count += 1;
                cityGroups[city].devices.push(device);
            });
            
            // 转换为离线地图需要的格式
            const positions = ['north', 'east', 'south', 'west', 'center', 'northeast', 'northwest', 'southeast', 'southwest'];
            let posIndex = 0;
            
            return Object.entries(cityGroups).map(([name, data]) => {
                const pos = positions[posIndex % positions.length];
                posIndex++;
                return {
                    name,
                    class: pos,
                    devices: data.count
                };
            });
        }
    },
    beforeDestroy() {
        console.log('销毁地图组件');
        // 销毁地图实例
        if (this.map) {
            this.map.destroy();
            this.map = null;
        }
        // 移除全局回调
        if (window.initAMap) {
            delete window.initAMap;
        }
    }
}
</script>
<style lang="scss" scoped>
.map-container {
    height: 100%;
    width: 100%;
    position: relative;
}

.map-content {
    height: 100%;
    width: 100%;
}

.map-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(255, 255, 255, 0.7);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 999;
}

.map-loading {
    padding: 15px 30px;
    background-color: rgba(0, 0, 0, 0.6);
    color: white;
    border-radius: 4px;
    font-size: 14px;
}

/* 离线地图样式 */
.offline-map {
    width: 100%;
    height: 100%;
    background-color: #f5f5f5;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.map-title {
    text-align: center;
    padding: 10px;
    background-color: #2c3e50;
    color: white;
    font-weight: bold;
}

.map-content {
    flex: 1;
    position: relative;
    background-color: #e8f4f8;
    display: flex;
    justify-content: center;
    align-items: center;
}

.map-background {
    position: absolute;
    top: 10%;
    left: 10%;
    right: 10%;
    bottom: 10%;
    background-color: #d3eaf2;
    border: 2px solid #aad4e0;
    border-radius: 50%;
    z-index: 1;
}

.city-marker {
    position: absolute;
    padding: 5px 10px;
    background-color: #3498db;
    color: white;
    border-radius: 4px;
    font-size: 12px;
    z-index: 2;
    cursor: pointer;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
    transition: all 0.3s;
}

.city-marker:hover {
    transform: scale(1.1);
    background-color: #2980b9;
}

.north {
    top: 20%;
    left: 50%;
    transform: translateX(-50%);
}

.south {
    bottom: 20%;
    left: 45%;
    transform: translateX(-50%);
}

.east {
    top: 40%;
    right: 25%;
}

.west {
    top: 40%;
    left: 25%;
}

.center {
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

.northeast {
    top: 30%;
    right: 20%;
}

.northwest {
    top: 30%;
    left: 20%;
}

.southeast {
    bottom: 30%;
    right: 20%;
}

.southwest {
    bottom: 30%;
    left: 20%;
}

/* 信息窗体样式 */
:deep(.info-window) {
    padding: 0;
    border-radius: 4px;
    border: 1px solid #ccc;
    background-color: white;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}

:deep(.info-title) {
    background-color: #3498db;
    color: white;
    padding: 8px 10px;
    font-size: 14px;
    font-weight: bold;
    border-radius: 4px 4px 0 0;
}

:deep(.info-body) {
    padding: 10px;
    font-size: 12px;
    
    p {
        margin: 5px 0;
    }
}
</style>







